<template>
  <tui-drawer
    mode="bottom"
    :maskZIndex="999990"
    :zIndex="999999"
    :visible="visible"
    @close="closeDrawer"
  >
    <view class="container">
      <view class="header">
        <text class="title">请选择地区</text>
        <text class="confirm" @click="handleConfirm">确定</text>
      </view>
      <view class="content-wrapper">
        <view class="columns-wrapper">
          <!-- 左侧列 -->
          <scroll-view
            class="column left-column"
            scroll-y
            :scroll-top="leftScrollTop"
            @scroll="handleScroll('left', $event)"
          >
            <view
              v-for="(item, index) in leftList"
              :key="item.id"
              :class="['item', { active: selectedLeftIndex === index }]"
            >
              {{ item.name }}
            </view>
          </scroll-view>

          <!-- 右侧列 -->
          <scroll-view
            class="column right-column"
            scroll-y
            :scroll-top="rightScrollTop"
            @scroll="handleScroll('right', $event)"
          >
            <view
              v-for="(item, index) in rightList"
              :key="item.id"
              :class="['item', { active: selectedRightIndex === index }]"
            >
              {{ item.name }}
            </view>
          </scroll-view>

          <!-- 中间指示框 -->
          <view class="indicator-box">
            <view class="indicator-line"></view>
            <view class="indicator-line"></view>
          </view>
        </view>
      </view>
    </view>
  </tui-drawer>
</template>
<script> 
	import {getAreaList,getDistrictList} from "@/http/api/index/index.js"
export default {
  data() {
    return {
      leftList: [],
      rightList: [],
      selectedLeftIndex: 0,
      selectedRightIndex: 0,
      itemHeight: 44, // 默认高度（rpx转换后的px值）
      containerHeight: 0,
      leftScrollTop: 0,
      selectedDistrict:'',
      selectedCity:'',
      rightScrollTop: 0,
      scrollLock: false
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.initScrollPosition();
          this.initDimensions(true);
        });
      }
    }, 
  },
  mounted() {
    this.initDimensions();
  },
  created() {
    this.fetchLeftList();
  },
  methods: {
    async initDimensions(forceUpdate = false) {
      if (!forceUpdate && this.itemHeight > 0 && this.containerHeight > 0) return;
      
      const query = uni.createSelectorQuery().in(this);
      try {
        const [containerRes, itemRes] = await Promise.all([
          new Promise(resolve => {
            query.select('.column')
              .boundingClientRect(res => resolve(res))
              .exec()
          }),
          new Promise(resolve => {
            query.select('.item')
              .boundingClientRect(res => resolve(res))
              .exec()
          })
        ]);

        this.itemHeight = Math.ceil(itemRes?.[0]?.height || 44) + 1; // 补偿1像素误差
        this.containerHeight = containerRes?.[0]?.height || 0; 
      } catch (error) {
        console.error('尺寸初始化失败:', error);
      }
    },

    closeDrawer() {
      this.selectedCity=this.leftList[this.selectedLeftIndex]
      this.selectedDistrict=this.rightList[this.selectedRightIndex]
      this.$emit("clear",{ city:  this.selectedCity, district:  this.selectedDistrict });
    },
    initScrollPosition() {
      this.leftScrollTop = this.selectedLeftIndex * this.itemHeight;
      this.rightScrollTop = this.selectedRightIndex * this.itemHeight;
    },
    async fetchLeftList() {
      try {  
          await getAreaList({level:'city'}).then(res=>{
              if(res.code==200){
                this.leftList = res.data
                this.leftList.push({
                  adcode: "110000",
                  id: 1,
                  level: "province",
                  name: "",
                  pid: "1",
                  status: "0"
                })
              }
         })
          await this.$nextTick();
          if (this.leftList.length > 0) {
            await this.fetchRightList(this.leftList[0].name);
          } 
      } catch (error) {
        console.error("请求失败:", error);
      }
    },
    async fetchRightList(cityName) {
    try {  
      await getDistrictList({cityName}).then(res=>{
              if(res.code==200){
               let data=res.data
               data.unshift({
                 name:'全部',
                 cityNmae:cityName
               })
               data.push({
                 name:'',
               })
               this.rightList =data
            }
        })
 
        this.selectedRightIndex = 0;
        
        await this.$nextTick();
        await this.initDimensions(true);
        this.rightScrollTop = 0; // 重置滚动位置
    } catch (error) {
      console.error("请求失败:", error);
    }
  },
 
 // 修改滚动处理逻辑
handleScroll(type, event) {
  if (this.scrollLock || !event.detail) return;
  this.scrollLock = true;

  const scrollTop = event.detail.scrollTop;
  const list = type === 'left' ? this.leftList : this.rightList;
  const maxIndex = list.length - 1;
  
  // 计算当前中心点位置（相对于列表顶部）
  const centerPos = scrollTop + this.containerHeight / 2;
  
  // 计算当前选中索引
  let currentIndex = Math.round(centerPos / this.itemHeight);
  currentIndex = Math.max(0, Math.min(currentIndex, maxIndex));

  this.$nextTick(() => {
    if (type === 'left') {
      if (this.selectedLeftIndex !== currentIndex) {
        this.selectedLeftIndex = currentIndex;
        if(!this.leftList[currentIndex].name){
          return false
        }
        this.fetchRightList(this.leftList[currentIndex].name);
      }
      // 对齐到精确位置
      this.leftScrollTop = currentIndex * this.itemHeight;
    } else {
      this.selectedRightIndex = currentIndex;
      this.rightScrollTop = currentIndex * this.itemHeight;
    }
    this.selectedCity=this.leftList[this.selectedLeftIndex]
    this.selectedDistrict=this.rightList[this.selectedRightIndex]
    this.scrollLock = false;
  });
},
    handleConfirm() {
      this.selectedCity=this.leftList[this.selectedLeftIndex];
      this.selectedDistrict= this.rightList[this.selectedRightIndex];
      console.log( this.selectedCity, this.selectedDistrict,'selectedDistrict')
      this.$emit("confirm", { city:  this.selectedCity, district:  this.selectedDistrict });
      this.closeDrawer();
    },
  },
};

</script>

<style scoped>
.container {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 2rpx solid #eee;
}

.title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.confirm {
  font-size: 32rpx;
  color: #007aff;
}

.content-wrapper {
  height:480rpx; 
}

.columns-wrapper {
  display: flex;
  height: 160rpx;
  position: relative;
}

.column {
  flex: 1;
  height: 100%;
  padding:  160rpx 0 160rpx 0;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
}

.item {
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 30rpx;
  color: rgba(153, 153, 153, 0.6);
  transition: all 0.3s ease;
  box-sizing: border-box;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item.active {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
  transform: scale(1.1);
  opacity: 1 !important;
}

.indicator-box {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 60rpx;
  transform: translateY(-50%);
  pointer-events: none;
  z-index: 2;
} 

.indicator-line:first-child {
  top: 0;
}

.indicator-line:last-child {
  bottom: 0;
}

.columns-wrapper::before,
.columns-wrapper::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  height: 120rpx;
  z-index: 1;
  pointer-events: none;
}

.columns-wrapper::before {
  top: 0;
  background: linear-gradient(
    to bottom, 
    rgba(255,255,255,1) 30%,
    rgba(255,255,255,0) 100%
  );
}

.columns-wrapper::after {
  bottom: 0;
  background: linear-gradient(
    to top, 
    rgba(255,255,255,1) 30%,
    rgba(255,255,255,0) 100%
  );
}
</style>